<?php

namespace app;

use app\util\CallFun;
use app\util\Task;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Http\Server;
use Swoole\Timer;

class Main
{
    private Server $server;

    public function __construct()
    {
        require 'common.php';
        $this->server = new Server('0.0.0.0', '9002');
        $this->server->on('Start', [$this, 'onStart']);
        $this->server->on('Request', [$this, 'onRequest']);
    }

    public function start()
    {
        // Run worker
        Timer::tick(1000, [Task::class, 'run']);
        $this->server->start();
    }

    final public function onStart(Server $serv)
    {
//        cli_set_process_title('sign-worker');
//        $pid = "{$serv->master_pid}\n{$serv->manager_pid}";
//        file_put_contents('/run/swooletask.pid', $pid);
        echo "服务已启动\n";
    }

    final public function onRequest(Request $request, Response $response)
    {
        try {
            echo "接口请求:{$request->server['request_uri']}\n";
            $callFun = new CallFun();
            $callFun->call($request, $response);
        } catch (\Throwable $exception) {
            var_dump($exception->getMessage());
            $response->end(json_encode(['code' => -1, 'message' => 'method not found']));
        }
    }

}